﻿using System.Globalization;
using System.Windows;
using System.Windows.Data;
using GraphShape.Algorithms.Layout;
using GraphShape.Controls.Converters;
using GraphShape.Controls.Extensions;
using Point = GraphShape.Point;
using Size = GraphShape.Size;


namespace KinonekoSoftware.Studio.Resources.Converters
{
    public class OrthogonalEdgeGenerator : EdgeGenerator, IMultiValueConverter
    {
        #region IMultiValueConverter

        /// <inheritdoc />
        /// <exception cref="T:System.ArgumentException">
        /// At least one of 9 arguments is missing.
        /// pos (1,2), size (3,4) of source; pos (5,6), size (7,8) of target; routeInformation (9)
        /// </exception>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values is null)
                return new PathFigureCollection(0);

            if (values.Length != 9)
            {
                throw new ArgumentException(
                                            $"{nameof(OrthogonalEdgeGenerator)} must have 9 parameters: pos (1,2), size (3,4) of source; pos (5,6), size (7,8) of target; routeInformation (9).",
                                            nameof(values));
            }
            
            ExtractValues(values, out var sX, out var sY, out var tX, out var tY, out var offsetY);

            var midY     = (int)(Math.Abs(sY - tY) / 2d) + sY;
            var segments = new PathSegment[3];
            var start    = new System.Windows.Point(sX, sY + offsetY);
            var point    = new System.Windows.Point(sX, midY);

            segments[0] = new LineSegment(point, true);
            
            
            point.X     = tX;
            point.Y     = midY;
            segments[1] = new LineSegment(point, true);
            
            
            point.X     = tX;
            point.Y     = tY - offsetY;
            segments[2] = new LineSegment(point, true);

            var pathCollection = new PathFigureCollection(2)
            {
                new PathFigure(start, segments, false),
            };

            return pathCollection;
        }

        /// <inheritdoc />
        /// <exception cref="T:System.NotSupportedException">This method is not supported.</exception>
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("Path to edge route conversion not supported.");
        }

        #endregion
    }
}